import { useState } from 'react'
import { LeftOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom'
import './kdxq.scss'
import { RightOutlined, MinusOutlined, PlusOutlined } from '@ant-design/icons'

interface CartItem {
    id: number
    name: string
    price: number
    quantity: number
    maxQuantity: number
    category: string
}

interface ExamItem {
    id: number
    name: string
    price: number
    quantity: number
    maxQuantity: number
    category: string
    hasPrecautions: boolean
}

interface TestItem {
    id: number
    name: string
    price: number
    quantity: number
    maxQuantity: number
    category: string
}

function Kdxq() {
    const navigate = useNavigate()
    const [activeTab, setActiveTab] = useState('药品')
    const [activeCategory, setActiveCategory] = useState('新冠预防中药')
    const [activeExamCategory, setActiveExamCategory] = useState('心电血压')
    const [activeTestCategory, setActiveTestCategory] = useState('血常规+生化检查')
    const [showSelectedModal, setShowSelectedModal] = useState(false) // 显示已选项目模态框
    // 从本地存储加载数据，如果没有则使用默认值
    const getInitialCartItems = () => {
        const saved = localStorage.getItem('kdxq_cartItems')
        if (saved) {
            return JSON.parse(saved)
        }
        return [
            { id: 1, name: '新冠预防中药 (正常人群) 1袋', price: 10.08, quantity: 1, maxQuantity: 5, category: '新冠预防中药' },
            { id: 2, name: '新冠预防中药 (体弱人群) 1袋', price: 11.80, quantity: 1, maxQuantity: 5, category: '新冠预防中药' },
            { id: 3, name: '新冠预防中药 (儿童人群) 1袋', price: 9.80, quantity: 0, maxQuantity: 5, category: '新冠预防中药' },
            { id: 4, name: '感冒清热颗粒 10g*12袋', price: 15.50, quantity: 0, maxQuantity: 3, category: '感冒用药' },
            { id: 5, name: '板蓝根颗粒 10g*20袋', price: 12.80, quantity: 0, maxQuantity: 5, category: '感冒用药' },
            { id: 6, name: '999感冒灵颗粒 10g*9袋', price: 18.60, quantity: 0, maxQuantity: 3, category: '感冒用药' },
            { id: 7, name: '阿莫西林胶囊 0.25g*24粒', price: 8.90, quantity: 0, maxQuantity: 2, category: '普通用药' },
            { id: 8, name: '布洛芬缓释胶囊 0.3g*20粒', price: 22.50, quantity: 0, maxQuantity: 2, category: '普通用药' }
        ]
    }

    const [cartItems, setCartItems] = useState<CartItem[]>(getInitialCartItems)

    // 从本地存储加载检查项目数据
    const getInitialExamItems = (): ExamItem[] => {
        const saved = localStorage.getItem('kdxq_examItems')
        if (saved) {
            return JSON.parse(saved)
        }
        return [
            { id: 1, name: '动态心电图', price: 150.00, quantity: 0, maxQuantity: 1, category: '心电血压', hasPrecautions: true },
            { id: 2, name: '12导同步心电图检查', price: 30.00, quantity: 0, maxQuantity: 1, category: '心电血压', hasPrecautions: false },
            { id: 3, name: '胸部X光片', price: 80.00, quantity: 0, maxQuantity: 1, category: '放射普放', hasPrecautions: false },
            { id: 4, name: '腹部B超', price: 120.00, quantity: 0, maxQuantity: 1, category: '超声检查', hasPrecautions: true }
        ]
    }

    const [examItems, setExamItems] = useState<ExamItem[]>(getInitialExamItems)

    // 从本地存储加载检验项目数据
    const getInitialTestItems = (): TestItem[] => {
        const saved = localStorage.getItem('kdxq_testItems')
        if (saved) {
            return JSON.parse(saved)
        }
        return [
            { id: 1, name: '血常规', price: 15.00, quantity: 1, maxQuantity: 1, category: '血常规+生化检查' },
            { id: 2, name: '血常规+网织红细胞', price: 38.00, quantity: 1, maxQuantity: 1, category: '血常规+生化检查' },
            { id: 3, name: '肝功', price: 38.00, quantity: 1, maxQuantity: 1, category: '血常规+生化检查' },
            { id: 4, name: '肾功', price: 24.00, quantity: 1, maxQuantity: 1, category: '血常规+生化检查' },
            { id: 5, name: '血糖', price: 12.00, quantity: 0, maxQuantity: 1, category: '血常规+生化检查' },
            { id: 6, name: '血脂', price: 45.00, quantity: 0, maxQuantity: 1, category: '血常规+生化检查' },
            { id: 7, name: '免疫球蛋白', price: 60.00, quantity: 0, maxQuantity: 1, category: '免疫血液检查' },
            { id: 8, name: '补体C3', price: 25.00, quantity: 0, maxQuantity: 1, category: '免疫血液检查' },
            { id: 9, name: '补体C4', price: 25.00, quantity: 0, maxQuantity: 1, category: '免疫血液检查' },
            { id: 10, name: '身高体重', price: 5.00, quantity: 0, maxQuantity: 1, category: '体检检查' },
            { id: 11, name: '血压测量', price: 8.00, quantity: 0, maxQuantity: 1, category: '体检检查' },
            { id: 12, name: '视力检查', price: 10.00, quantity: 0, maxQuantity: 1, category: '体检检查' }
        ]
    }

    const [testItems, setTestItems] = useState<TestItem[]>(getInitialTestItems)

    const categories = [
        { id: '新冠预防中药', name: '新冠预防中药' },
        { id: '普通用药', name: '普通用药' },
        { id: '感冒用药', name: '感冒用药 (非处方)' }
    ]

    const examCategories = [
        { id: '心电血压', name: '心电血压' },
        { id: '放射普放', name: '放射普放' },
        { id: '超声检查', name: '超声检查' }
    ]

    const testCategories = [
        { id: '血常规+生化检查', name: '血常规+生化检查' },
        { id: '免疫血液检查', name: '免疫血液检查' },
        { id: '体检检查', name: '体检检查' }
    ]

    const updateQuantity = (id: number, newQuantity: number) => {
        const newItems = cartItems.map(item =>
            item.id === id
                ? { ...item, quantity: Math.max(0, Math.min(newQuantity, item.maxQuantity)) }
                : item
        )
        setCartItems(newItems)
        localStorage.setItem('kdxq_cartItems', JSON.stringify(newItems))
    }

    const updateExamQuantity = (id: number, newQuantity: number) => {
        const newItems = examItems.map(item =>
            item.id === id
                ? { ...item, quantity: Math.max(0, Math.min(newQuantity, item.maxQuantity)) }
                : item
        )
        setExamItems(newItems)
        localStorage.setItem('kdxq_examItems', JSON.stringify(newItems))
    }

    const updateTestQuantity = (id: number, newQuantity: number) => {
        const newItems = testItems.map(item =>
            item.id === id
                ? { ...item, quantity: Math.max(0, Math.min(newQuantity, item.maxQuantity)) }
                : item
        )
        setTestItems(newItems)
        localStorage.setItem('kdxq_testItems', JSON.stringify(newItems))
    }


    // 根据当前选中的分类过滤产品
    const filteredItems = cartItems.filter(item => item.category === activeCategory)
    const selectedItems = cartItems.filter(item => item.quantity > 0)

    // 根据当前选中的分类过滤检查项目
    const filteredExamItems = examItems.filter(item => item.category === activeExamCategory)
    const selectedExamItems = examItems.filter(item => item.quantity > 0)

    // 根据当前选中的分类过滤检验项目
    const filteredTestItems = testItems.filter(item => item.category === activeTestCategory)
    const selectedTestItems = testItems.filter(item => item.quantity > 0)

    // 计算所有页面的总数量和总价格（联动显示）
    const allSelectedItems = [
        ...selectedItems.map(item => ({ ...item, type: '药品' })),
        ...selectedExamItems.map(item => ({ ...item, type: '检查' })),
        ...selectedTestItems.map(item => ({ ...item, type: '检验' }))
    ]
    const allTotalPrice = allSelectedItems.reduce((sum, item) => sum + (item.price * item.quantity), 0)
    const allTotalQuantity = allSelectedItems.reduce((sum, item) => sum + item.quantity, 0)
    return (
        <div className='kdxq'>
            <div className='kdxq-top'>
                <span><LeftOutline className='kdxq-top-left' onClick={() => navigate(-1)} /></span>
                <span className='kdxq-top-title'>开单详情</span>
            </div>
            <div className='kdxq-bg'>
                <div className='kdxq-nav'>
                    <div className='nav-tabs'>
                        <div
                            className={`nav-tab ${activeTab === '药品' ? 'active' : ''}`}
                            onClick={() => setActiveTab('药品')}
                        >
                            <span className='tab-text'>药品</span>
                            {activeTab === '药品' && <div className='tab-underline'></div>}
                        </div>
                        <div
                            className={`nav-tab ${activeTab === '检查' ? 'active' : ''}`}
                            onClick={() => setActiveTab('检查')}
                        >
                            <span className='tab-text'>检查</span>
                            {activeTab === '检查' && <div className='tab-underline'></div>}
                        </div>
                        <div
                            className={`nav-tab ${activeTab === '检验' ? 'active' : ''}`}
                            onClick={() => setActiveTab('检验')}
                        >
                            <span className='tab-text'>检验</span>
                            {activeTab === '检验' && <div className='tab-underline'></div>}
                        </div>
                    </div>
                    <div className='nav-link' onClick={() => navigate('/kdjl')}>
                        <span className='link-text'>开单记录{<RightOutlined />}</span>
                    </div>
                </div>

                {activeTab === '药品' && (
                    <div className='kdxq-content'>
                        <div className='sidebar'>
                            <div className='category-list'>
                                {categories.map(category => (
                                    <div
                                        key={category.id}
                                        className={`category-item ${activeCategory === category.id ? 'active' : ''}`}
                                        onClick={() => setActiveCategory(category.id)}
                                    >
                                        {category.name}
                                    </div>
                                ))}
                            </div>
                        </div>

                        <div className='main-content'>
                            <div className='product-list'>
                                {filteredItems.length > 0 ? (
                                    filteredItems.map(item => (
                                        <div key={item.id} className='product-card'>
                                            <div className='product-image'>
                                                <div className='image-placeholder'></div>
                                            </div>
                                            <div className='product-info'>
                                                <div className='product-title'>{item.name}</div>
                                                <div className='product-description'>
                                                    {item.category === '新冠预防中药' && '功效: 主要提高免疫力，预防新冠疾病'}
                                                    {item.category === '感冒用药' && '功效: 清热解毒, 缓解感冒症状'}
                                                    {item.category === '普通用药' && '功效: 消炎止痛, 治疗常见疾病'}
                                                </div>
                                                <div className='price-row'>
                                                    <div className='product-price'>¥{item.price.toFixed(2)}</div>
                                                    <div className='quantity-selector'>
                                                        <button
                                                            className='qty-btn minus'
                                                            onClick={() => updateQuantity(item.id, item.quantity - 1)}
                                                            disabled={item.quantity <= 0}
                                                        >
                                                            <MinusOutlined />
                                                        </button>
                                                        <input
                                                            type="number"
                                                            value={item.quantity}
                                                            onChange={(e) => updateQuantity(item.id, parseInt(e.target.value) || 0)}
                                                            className='qty-input'
                                                        />
                                                        <button
                                                            className='qty-btn plus'
                                                            onClick={() => updateQuantity(item.id, item.quantity + 1)}
                                                            disabled={item.quantity >= item.maxQuantity}
                                                        >
                                                            <PlusOutlined />
                                                        </button>
                                                    </div>
                                                </div>
                                                <div className='product-tags'>
                                                    <span className='tag prescription'>
                                                        {item.category === '感冒用药' ? '非处方药' : '处方药'}
                                                    </span>
                                                    {item.maxQuantity <= 5 && <span className='tag limit'>限购{item.maxQuantity}{item.category === '新冠预防中药' ? '袋' : '盒'}</span>}
                                                </div>
                                            </div>
                                        </div>
                                    ))
                                ) : (
                                    <div className='empty-state'>
                                        <div className='empty-text'>暂无项目</div>
                                        <div className='empty-desc'>该分类下暂时没有可用的药品</div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                )}

                {activeTab === '检查' && (
                    <div className='kdxq-content'>
                        <div className='sidebar'>
                            <div className='category-list'>
                                {examCategories.map(category => (
                                    <div
                                        key={category.id}
                                        className={`category-item ${activeExamCategory === category.id ? 'active' : ''}`}
                                        onClick={() => setActiveExamCategory(category.id)}
                                    >
                                        {category.name}
                                    </div>
                                ))}
                            </div>
                        </div>

                        <div className='main-content'>
                            <div className='product-list'>
                                {filteredExamItems.length > 0 ? (
                                    filteredExamItems.map(item => (
                                        <div key={item.id} className='exam-card'>
                                            <div className='exam-info'>
                                                <div className='exam-title'>{item.name}</div>
                                                <div className='exam-price'>¥ {item.price.toFixed(2)}/次</div>
                                                {item.hasPrecautions && (
                                                    <div className='exam-tag'>注意事项</div>
                                                )}
                                            </div>
                                            <div className='exam-selector'>
                                                <button
                                                    className={`select-btn ${item.quantity > 0 ? 'selected' : ''}`}
                                                    onClick={() => updateExamQuantity(item.id, item.quantity > 0 ? 0 : 1)}
                                                >
                                                    {item.quantity > 0 ? '✓' : '+'}
                                                </button>
                                            </div>
                                        </div>
                                    ))
                                ) : (
                                    <div className='empty-state'>
                                        <div className='empty-text'>暂无项目</div>
                                        <div className='empty-desc'>该分类下暂时没有可用的检查项目</div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                )}

                {activeTab === '检验' && (
                    <div className='kdxq-content'>
                        <div className='sidebar'>
                            <div className='category-list'>
                                {testCategories.map(category => (
                                    <div
                                        key={category.id}
                                        className={`category-item ${activeTestCategory === category.id ? 'active' : ''}`}
                                        onClick={() => setActiveTestCategory(category.id)}
                                    >
                                        {category.name}
                                    </div>
                                ))}
                            </div>
                        </div>

                        <div className='main-content'>
                            <div className='product-list'>
                                {filteredTestItems.length > 0 ? (
                                    filteredTestItems.map(item => (
                                        <div key={item.id} className='test-card'>
                                            <div className='test-info'>
                                                <div className='test-title'>{item.name}</div>
                                                <div className='test-price'>¥ {item.price.toFixed(2)}/次</div>
                                            </div>
                                            <div className='test-selector'>
                                                <button
                                                    className={`select-btn ${item.quantity > 0 ? 'selected' : ''}`}
                                                    onClick={() => updateTestQuantity(item.id, item.quantity > 0 ? 0 : 1)}
                                                >
                                                    {item.quantity > 0 ? '✓' : '+'}
                                                </button>
                                            </div>
                                        </div>
                                    ))
                                ) : (
                                    <div className='empty-state'>
                                        <div className='empty-text'>暂无项目</div>
                                        <div className='empty-desc'>该分类下暂时没有可用的检验项目</div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                )}
            </div>

            {(activeTab === '药品' || activeTab === '检查' || activeTab === '检验') && allTotalQuantity > 0 && (
                <div className='bottom-bar'>
                    <div className='order-summary' onClick={() => setShowSelectedModal(true)}>
                        <div className='summary-icon'>
                            <div className='badge'>
                                {allTotalQuantity}
                            </div>
                        </div>
                        <div className='summary-text'>
                            <div className='selected-count'>
                                已选{allTotalQuantity} 项
                            </div>
                            <div className='total-price'>
                                合计: <span className='price'>
                                    ¥ {allTotalPrice.toFixed(2)}
                                </span>
                            </div>
                        </div>
                    </div>
                    <button className='submit-btn' onClick={() => navigate('/kdqr', { 
                      state: { selectedItems: allSelectedItems } 
                    })}>提交</button>
                </div>
            )}

            {/* 已选项目模态框 */}
            {showSelectedModal && (
                <div className="modal-overlay" onClick={() => setShowSelectedModal(false)}>
                    <div className="modal-content selected-modal" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <span className="modal-title">已选项目</span>
                            <button className="close-btn" onClick={() => setShowSelectedModal(false)}>×</button>
                        </div>
                        <div className="selected-items-list">
                            {allSelectedItems.map((item, index) => (
                                <div key={`${item.id}-${index}`} className="selected-item">
                                    <div className="item-info">
                                        <div className="item-name">{item.name}</div>
                                        <div className="item-price">¥ {item.price.toFixed(2)}</div>
                                    </div>
                                    <div className="quantity-controls">
                                        <button 
                                            className="quantity-btn minus"
                                            onClick={() => {
                                                if (activeTab === '药品') {
                                                    updateQuantity(item.id, item.quantity - 1)
                                                } else if (activeTab === '检查') {
                                                    updateExamQuantity(item.id, item.quantity - 1)
                                                } else if (activeTab === '检验') {
                                                    updateTestQuantity(item.id, item.quantity - 1)
                                                }
                                            }}
                                            disabled={item.quantity <= 0}
                                        >
                                            -
                                        </button>
                                        <span className="quantity-display">{item.quantity}</span>
                                        <button 
                                            className="quantity-btn plus"
                                            onClick={() => {
                                                if (activeTab === '药品') {
                                                    updateQuantity(item.id, item.quantity + 1)
                                                } else if (activeTab === '检查') {
                                                    updateExamQuantity(item.id, item.quantity + 1)
                                                } else if (activeTab === '检验') {
                                                    updateTestQuantity(item.id, item.quantity + 1)
                                                }
                                            }}
                                            disabled={item.quantity >= item.maxQuantity}
                                        >
                                            +
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                        <div className="modal-footer">
                            <div className="total-summary">
                                <span className="total-items">共 {allTotalQuantity} 项</span>
                                <span className="total-amount">总计: ¥ {allTotalPrice.toFixed(2)}</span>
                            </div>
                        </div>
                    </div>
                </div>
            )}

        </div>
    )
}

export default Kdxq